import ChatHandler from './model/ChatHandler'
import TransHandler from './model/TransHandler'
import SystemHandler from './model/SystemHandler'
import AfterSalesHandler from './model/AfterSalesHandler'
import SettlementBillHandler from './model/SettlementBillHandler'
import SkuCountHandler from './model/SkuCountHandler'
import ImageCacheHandler from './model/ImageCacheHandler'

import MSocket from '../socket/MSocket'
import { useUserStore, useChatStore, useNoticeStore } from '@/store'

export default class ImHandler {
    sqlite: any
    appIsHide: boolean
    curOther: any
    curNotice: any
    unreadChatInitCallBack: any
    messageCallBack: any
    isOtherLogin: boolean
    isConnected: boolean
    chat: any
    trans: any
    system: any
    afterSales: any
    settlementBill: any
    sku: any
    socket: any
    userStore: any
    chatStore: any
    noticeStore: any
    img: any

    constructor(sqlite: any) {
        this.sqlite = sqlite
        this.chat = new ChatHandler(sqlite)
        this.trans = new TransHandler(sqlite)
        this.system = new SystemHandler(sqlite)
        this.afterSales = new AfterSalesHandler(sqlite)
        this.settlementBill = new SettlementBillHandler(sqlite)
        this.sku = new SkuCountHandler(sqlite)
        this.img = new ImageCacheHandler(sqlite)
        this.socket = new MSocket()
        this.appIsHide = false
        this.unreadChatInitCallBack = undefined
        this.messageCallBack = undefined
        this.curOther = undefined
        this.curNotice = undefined
        // 其他设备登录标识
        this.isOtherLogin = false
        // 连接状态
        this.isConnected = false
        this.userStore = useUserStore()
        this.chatStore = useChatStore()
        this.noticeStore = useNoticeStore()
    }

    setUnreadChatInitCallBack(call: any) {
        this.unreadChatInitCallBack = call
    }

    setMessageCallBack({ other, notice, call }: { other: any; notice: any; call: Function }) {
        this.curOther = other
        this.curNotice = notice
        this.messageCallBack = call
    }

    closeSocket(isLogOut: boolean) {
        this.isConnected = false
        try {
            this.socket.closeSocket(isLogOut)
        } catch (e) {
            //TODO handle the exception
        }
    }

    openSocket() {
        let user = this.userStore.userinfo
        let _this = this
        this.socket.startSocket(user, {
            open() {
                // 取消其他设备登录标记
                _this.isOtherLogin = false
                // 设置连接状态
                _this.isConnected = true
                _this.socket.setIsLogOut(false)
                // 单聊
                _this.chatStore.unreadCountClear().then(() => {
                    _this.unreadChatInit()
                })

                // 订单交易
                _this.noticeStore.transInit({ userId: user.userId })
                // 通知消息
                _this.noticeStore.systemInit({ userId: user.userId })
                // 售后通知
                _this.noticeStore.afterSalesInit({ userId: user.userId })
                // 账单通知
                _this.noticeStore.settlementBillInit({ userId: user.userId })
            },
            message(data: any) {
                // console.log(data)
                if (data.model === 2) {
                    // 聊天信息
                    let obj = JSON.parse(data.data)
                    if (obj.chatType === 0) {
                        //单聊
                        _this.dealNewChat(obj.chat)
                    }
                } else if (data.model === 3) {
                    // 状态通知
                    let obj = JSON.parse(data.data)
                    if (obj.chatType === 0) {
                        //单聊
                        _this.dealStatusChat(obj.statusChildren)
                    }
                } else if (data.model === 4) {
                    // 订单交易通知
                    let obj = JSON.parse(data.data)
                    _this.dealNewTrans(obj)
                } else if (data.model === 5) {
                    // 系统通知
                    let obj = JSON.parse(data.data)
                    _this.dealNewSystem(obj)
                } else if (data.model === 6) {
                    // 售后通知
                    let obj = JSON.parse(data.data)
                    _this.dealNewAfterSales(obj)
                } else if (data.model === 7) {
                    // 账单通知
                    let obj = JSON.parse(data.data)
                    _this.dealNewSettlementBill(obj)
                } else if (data.model === 10) {
                    // 其他设备登录
                    console.log('其他设备登录了', data.data)
                    _this.isOtherLogin = true
                    this.userStore.LogOut().then(() => {
                        uni.$u.$showModal({
                            title: '温馨提示',
                            content: '您已断开连接，' + data.data,
                            showCancel: false,
                            confirmText: '重新登录',
                            success: () => {
                                uni.$u.$MRouter.login.to()
                            }
                        })
                    })
                }
            },
            close() {
                console.log('已断开连接')
                this.isConnected = false
                // if (!e.isLogOut) {}
            },
            error() {
                // console.error(err)
            }
        })
    }

    dealNewChat(chat: any) {
        console.log('新消息处理: ', chat)
        // chat的lastContent
        chat.lastContent = this.dealLastContent(chat.type, chat.contentObj)
        // 是否为当前聊天窗口消息
        if (this.curOther && this.curOther.user.id == chat.sender && this.messageCallBack) {
            chat.isRead = 1
            this.chat.addNewChat(chat).then((record: any) => {
                this.messageCallBack(record)
                // 发送阅读状态
                uni.$u.$api.ImChat.readChat(chat.id)
            })
            // 聊天列表置顶
            //uni.$store.dispatch('addListByNewChat', {chat, isCur: true})
        } else {
            if (chat.lastContent != '结束服务') {
                // 添加消息个数
                this.chatStore.unreadCountChatAdd(1)
                // 更新 消息中心页面 最新消息内容
                this.chatStore.updateLastMessage(chat)

                this.updateTabBarText()
            }
        }
        if (chat.lastContent != '结束服务') {
            // 创建本地消息
            this.createMessage({ chat })
        }
    }

    dealStatusChat(statusArr: Array<any>) {
        if (statusArr && statusArr.length > 0) {
            // 优先更新本地数据
            let chatArr = statusArr.map(it => {
                return {
                    id: it.id,
                    isRead: it.readStatus,
                    updateTime: uni.$u.$timeUtil.formatDate(it.lastTime),
                    delFlag: it.delFlag ? 1 : 0
                }
            })
            this.chat.statusUpdate(chatArr).then(() => {
                // 如果是当前页面，页面重新渲染
                if (this.curOther && this.messageCallBack) {
                    this.messageCallBack(chatArr, true)
                }
            })
        }
    }

    dealNewTrans(trans: any) {
        // 是否为当前通知窗口
        if (this.curNotice && this.curNotice.key === 4 && this.messageCallBack) {
            // 本地添加/更新消息，并更新阅读通知
            this.trans.dealUnreadByNewTrans(trans).then((ftrans: any) => {
                // 更新通知列表
                this.noticeStore.updateTrans({
                    lastContent: ftrans.title,
                    lastTime: ftrans.updateTime,
                    num: 0
                })
                this.messageCallBack(this.curNotice.key, ftrans)

                this.updateTabBarText()
            })
        } else {
            // 保存本地
            this.sqlite.imTrans.saveOrUpdateTrans([trans])
            // 更新通知列表
            this.noticeStore.updateTrans({
                lastContent: trans.title,
                lastTime: trans.updateTime,
                num: 1
            })
            this.updateTabBarText()
        }
        // 创建本地消息
        this.createMessage({ trans })
    }

    dealNewSystem(system: any) {
        // 是否为当前通知窗口
        if (this.curNotice && this.curNotice.key === 5 && this.messageCallBack) {
            // 本地添加/更新消息，并更新阅读通知
            this.system.dealUnreadByNewSystem(system).then((fSystem: any) => {
                // 更新通知列表
                this.noticeStore.updateSystem({
                    lastContent: fSystem.title,
                    lastTime: fSystem.updateTime,
                    num: 0
                })
                this.messageCallBack(this.curNotice.key, fSystem)

                this.updateTabBarText()
            })
        } else {
            // 保存本地
            this.sqlite.imSystem.saveOrUpdateSystem([system])
            // 更新通知列表
            this.noticeStore.updateSystem({
                lastContent: system.title,
                lastTime: system.updateTime,
                num: 1
            })
            this.updateTabBarText()
        }
        // 创建本地消息
        this.createMessage({ system })
    }

    dealNewAfterSales(afterSales: any) {
        // 是否为当前通知窗口
        if (this.curNotice && this.curNotice.key === 6 && this.messageCallBack) {
            // 本地添加/更新消息，并更新阅读通知
            this.afterSales.dealUnreadByNewAfterSales(afterSales).then((fAfterSales: any) => {
                // 更新通知列表
                this.noticeStore.updateAfterSales({
                    lastContent: fAfterSales.title,
                    lastTime: fAfterSales.updateTime,
                    num: 0
                })
                this.messageCallBack(this.curNotice.key, fAfterSales)

                this.updateTabBarText()
            })
        } else {
            // 保存本地
            this.sqlite.imAfterSales.saveOrUpdateAfterSales([afterSales])
            // 更新通知列表
            this.noticeStore.updateAfterSales({
                lastContent: afterSales.title,
                lastTime: afterSales.updateTime,
                num: 1
            })
            this.updateTabBarText()
        }
        // 创建本地消息
        this.createMessage({ afterSales })
    }

    dealNewSettlementBill(settlementBill: any) {
        // 是否为当前通知窗口
        if (this.curNotice && this.curNotice.key === 6 && this.messageCallBack) {
            // 本地添加/更新消息，并更新阅读通知
            this.settlementBill.dealUnreadByNewSettlementBill(settlementBill).then((fSettlementBill: any) => {
                // 更新通知列表
                this.noticeStore.updateSettlementBill({
                    lastContent: fSettlementBill.title,
                    lastTime: fSettlementBill.updateTime,
                    num: 0
                })
                this.messageCallBack(this.curNotice.key, fSettlementBill)

                this.updateTabBarText()
            })
        } else {
            // 保存本地
            this.sqlite.imSettlementBill.saveOrUpdateSettlementBill([settlementBill])
            // 更新通知列表
            this.noticeStore.updateSettlementBill({
                lastContent: settlementBill.title,
                lastTime: settlementBill.updateTime,
                num: 1
            })
            this.updateTabBarText()
        }
        // 创建本地消息
        this.createMessage({ settlementBill })
    }

    /**
     * 查询单聊未读消息列表
     */
    unreadChatInit() {
        // 初始化本地聊天列表
        uni.$u.$api.ImChat.unreadStaYwy().then((unreadStaYwy: any) => {
            if (unreadStaYwy) {
                // 循环未读数量并添加到聊天列表中
                let chatCount = 0
                // 处理最后消息内容
                unreadStaYwy.lastContent = this.dealLastContent(unreadStaYwy.type, unreadStaYwy.content)
                // 记录未读数量
                chatCount += unreadStaYwy.count ? unreadStaYwy.count : 0
                // 添加总未读数量
                this.chatStore.unreadCountChatAdd(chatCount)

                this.updateTabBarText()
            }
        })
    }

    loadNewChatRecords() {
        return new Promise((resolve, reject) => {
            if (this.curOther.type === 0) {
                this.chat.newList(this.curOther.user.id).then((records: any) => {
                    if (records && records.length > 0) {
                        // 处理掉未读消息数量
                        this.chatStore.unreadCountChatClear()
                        // this.updateTabBarText()
                        resolve(records)
                    } else {
                        resolve([])
                    }
                })
            }
        })
    }

    loadHistoryChatRecords(firstTime: any) {
        return new Promise((resolve, reject) => {
            if (this.curOther.type === 0) {
                this.chat.historyList(this.curOther.user.id, firstTime).then((records: any) => {
                    if (records && records.length > 0) {
                        resolve(records)
                    } else {
                        resolve([])
                    }
                })
            }
        })
    }

    dealLastContent(type: number, contentObj: any) {
        let lastContent = ''
        if (typeof contentObj === 'string') {
            contentObj = JSON.parse(contentObj)
        }
        switch (type) {
            case 1:
                lastContent = contentObj.c
                break
            case 2:
                lastContent = '[图片]'
                break
            case 3:
                lastContent = '[语音]'
                break
            case 4:
                lastContent = '[文件]'
                break
            case 5:
                lastContent = '[链接]'
                break
            default:
                break
        }
        return lastContent
    }

    dealPushContent(type: number, contentObj: any) {
        let pushContent = ''
        if (typeof contentObj === 'string') {
            contentObj = JSON.parse(contentObj)
        }
        switch (type) {
            case 1:
                pushContent = contentObj.c
                if (pushContent.length > 17) {
                    pushContent = pushContent.substr(0, 17) + '...'
                }
                break
            case 2:
                pushContent = '您收到了一条[图片]信息'
                break
            case 3:
                pushContent = '您收到了一条[语音]信息'
                break
            case 4:
                pushContent = '您收到了一条[文件]信息'
                break
            case 5:
                pushContent = '您收到了一条[链接]信息'
                break
            default:
                break
        }
        return pushContent
    }

    /**
     * 原先方法 会再次存储 最新的消息 不符合使用场景  因此写了新的方法 获取最新一条的聊天消息
     */
    getlastChatMessage(id: number | string) {
        return new Promise((resolve, reject) => {
            this.chat
                .getlastChatMessage(id)
                .then((record: any) => {
                    resolve(record)
                })
                .catch(() => {
                    reject()
                })
        })
    }

    /**
     * 创建本地消息
     */
    createMessage({ chat, trans, afterSales, system, settlementBill }: { chat?: any; trans?: any; afterSales?: any; system?: any; settlementBill?: any }) {
        // 只有后台运行才创建本地消息
        if (this.appIsHide) {
            if (chat) {
                let payload = {
                    messageType: 2,
                    title: '聊天消息',
                    content: this.dealPushContent(chat.type, chat.contentObj),
                    sender: chat.sender
                }
                let option = { title: payload.title }
                plus.push.createMessage(payload.content, JSON.stringify(payload), option)
            }
            if (trans) {
                let payload = {
                    messageType: 4,
                    title: '订单交易通知',
                    content: trans.title,
                    sender: 0
                }
                let option = { title: payload.title }
                plus.push.createMessage(payload.content, JSON.stringify(payload), option)
            }
            if (system) {
                let payload = {
                    messageType: 5,
                    title: '通知消息',
                    content: system.title,
                    sender: 0
                }
                let option = { title: payload.title }
                plus.push.createMessage(payload.content, JSON.stringify(payload), option)
            }
            if (afterSales) {
                let payload = {
                    messageType: 6,
                    title: '售后通知',
                    content: afterSales.title,
                    sender: 0
                }
                let option = { title: payload.title }
                plus.push.createMessage(payload.content, JSON.stringify(payload), option)
            }
            if (settlementBill) {
                let payload = {
                    messageType: 7,
                    title: '账单通知',
                    content: settlementBill.title,
                    sender: 0
                }
                let option = { title: payload.title }
                plus.push.createMessage(payload.content, JSON.stringify(payload), option)
            }
        }
    }

    updateTabBarText() {
        setTimeout(() => {
            let unreadCount = this.chatStore.unreadCount
            let notice = this.noticeStore.notice
            let num = unreadCount.chat + notice.trans.unread + notice.system.unread + notice.afterSales.unread + notice.settlementBill.unread
            // #ifdef APP-PLUS
            plus.runtime.setBadgeNumber(num, {
                title: '超凡云仓',
                content: ''
            })
            // #endif
        }, 100)
    }
}
